package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //新增分类
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增成功");
    }


    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> page(
            @RequestParam(name = "page",required = false,defaultValue = "1") Integer page,
            @RequestParam(name = "pageSize",required = false,defaultValue = "10") Integer pageSize){
        //构造分页对象
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //构造排序条件
        QueryWrapper<Category> queryWrapper =new QueryWrapper<>();
        //根据sort进行排序 进行降序 如果有相同的 根据更新时间排序
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }


    //根据id删除分类
    @DeleteMapping
    public R<String> delete(Long id){
      categoryService.remove(id);
        return R.success("删除分类成功");
    }

    //根据id修改 分类信息
    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息:{}",category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    //添加菜品的下拉框读取和排序 查询菜品的分类数据
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件查询
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件 判断tpye是否为空 如果不为空那么给type赋值
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //得出list集合
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
